﻿using System;

namespace ControleRepresentanteSync.Application.Wizard
{
    internal class WizardPresenter : PresenterBase<IWizardViewModel>
    {
        private readonly IWizardPageProvider m_PageProvider;

        public WizardPresenter(IWizardViewModel viewModel, IWizardPageProvider pageProvider)
            : base(viewModel)
        {
            m_PageProvider = pageProvider;
            ViewModel.CurrentPage = pageProvider.Current;
            UpdateCanGo();

            ViewModel.GoBack += ViewModelGoBack;
            ViewModel.GoForward += ViewModelGoForward;
            ViewModel.Cancel += ViewModelCancel;

            pageProvider.Changed += PageProviderChanged;
        }

        void PageProviderChanged(object sender, EventArgs e)
        {
            UpdateCanGo();
        }

        private void ViewModelCancel(object sender, EventArgs e)
        {
            ViewModel.FireClose(false);
            ViewModel.FireOnClose();
        }

        private void UpdateCanGo()
        {
            ViewModel.CanGoBack = m_PageProvider.CanGoBack;
            ViewModel.IsFinish = m_PageProvider.IsFinish;
        }

        private void ViewModelGoForward(object sender, EventArgs e)
        {
            if (ViewModel.CurrentPage.TryApply())
            {
                if (m_PageProvider.IsFinish)
                {
                    ViewModel.FireClose(true);
                }
                else
                {
                    ViewModel.CurrentPage = m_PageProvider.MoveNext();
                    UpdateCanGo();
                }
            }
        }

        private void ViewModelGoBack(object sender, EventArgs e)
        {
            ViewModel.CurrentPage = m_PageProvider.MoveBack();
            UpdateCanGo();
        }

        public override void Dispose()
        {
            base.Dispose();

            ViewModel.GoBack -= ViewModelGoBack;
            ViewModel.GoForward -= ViewModelGoForward;
            ViewModel.Cancel -= ViewModelCancel;

            m_PageProvider.Changed -= PageProviderChanged;

            m_PageProvider.Dispose();
        }
    }
}